/**
 * Created by hjqi on 2016/4/21.
 */
var logger = require('../log4js/log4js').logger('influxdb');
var config = require('../config/config').config;
var httpRequest = require('../common/httpRequest').httpRequest;
var _req = new httpRequest();
var qs = require('querystring');

function libInfluxdb(){

}

libInfluxdb.prototype.query = function(param){

    return new Promise(function (resolve, reject){
        var _url = 'http://'+config.influxdb.host+':'+config.influxdb.port+'/query?q='+param.q+'&db=cadvisor&_ts='+param._ts;
        _req._request(_url,'GET',{},'',function(ret){
            httpHandler( ret,resolve,reject ) ;
        });
    });

}


libInfluxdb.prototype.queryK8s = function(param,clusterId){
    if( clusterId !== undefined ){
        logger.info( "Cluster id "+ clusterId===undefined?"default":clusterId ) ;
    }else{
        logger.info("there is no clusterId ") ;
    }

    if( clusterId && clusterId !== "default" ){
        var clusterConfig = getClusterInfo( clusterId );
        return new Promise(function (resolve, reject){
            var _url = 'http://'+clusterConfig.influxdb.host+':'+clusterConfig.influxdb.port+'/query?q='+param.q+'&db=k8s';

            logger.debug( "influxdb access :" +_url ) ;
            _req._request(_url,'GET',{},'',function(ret){
                httpHandler( ret,resolve,reject ) ;
            });
        });

    }else{
        return new Promise(function (resolve, reject){
            var _url = 'http://'+config.influxdb.host+':'+config.influxdb.port+'/query?q='+param.q+'&db=k8s';
            _req._request(_url,'GET',{},'',function(ret){
                httpHandler( ret,resolve,reject ) ;
            });
        });
    }

}

function httpHandler(ret,resolve,reject){
    if( emptyResult(ret) ){
        var exception= {
          code:400,
          message:"Connection is refused!"
        };
        reject( exception ) ;
    }
    if(!ret || ret.statusCode !== 200)
    {
        logger.warn("InfluxDb reject the query because of ret="+ JSON.stringify(ret) ) ;
        reject(ret);
    }  else{
        logger.debug( "InfluxDb ret:"+JSON.stringify(ret) ) ;
        resolve(ret);
    }
}

function emptyResult(ret){
    if( !ret ){
        logger.error("Can't connect to "+config.influxdb.host) ;
        return true ;
    }
    return false ;
}
/**
 * since there is free-host and natureCloud cluster ,
 * so there will be different influx db and we need collect data from the free-host cluster
 */
function getClusterInfo( clusterId){
    //load cluster info by clusterId
    // var clusterMetaInfo = _k8s_adp.loadClusterInfo( clusterId ) ;
    //default port of influx db will be 8086
    var clusterConfig = {
        /*"influxdb":{
            "host": clusterId+'monitor.tunnel.naturecloud.io', //virtual domain name
            "port":"8080"
        }*/
        "influxdb":{
            "host": clusterId+'monitor.'+config.tunnel.domain, //virtual domain name
            "port":config.tunnel.port
        }
    };
    return clusterConfig ;
}

module.exports = libInfluxdb;